/**
 * @Author: langchenglai
 * @Date:   2018-05-29 10:50:24
 * @Email:  lclangcheng@gmail.com
 * @Filename: mail.js
 * @Last modified by:   lclangcheng
 * @Last modified time: 2018-09-26 16:58:58
 * @License: jin10
 * @Copyright: jin10
 */
'use strict'

const nodemailer = require('nodemailer')
const crypto = require('crypto')
const log = require('./log')

class Mail {
  constructor () {
    this.send = this.send.bind(this)
    this.contents = []
  }

  MD5 (str) {
    return crypto.createHash('md5').update(str).digest('hex')
  }

  async send (content, receiveMail = '178404539@qq.com') {
    let self = this
    const strContent = JSON.stringify(content)
    let transporter = nodemailer.createTransport({
      host: 'smtp.qq.com',
      port: 587,
      secure: false, // true for 465, false for other ports
      auth: {
        user: '858342842@qq.com', // generated ethereal user
        pass: 'oomcnaiwrykzbfge' // generated ethereal password
      }
    })
    // setup email data with unicode symbols
    let mailOptions = {
      from: 'Inspector <858342842@qq.com>', // sender address
      to: receiveMail, // list of receivers
      subject: 'Server WARNING', // Subject line
      text: strContent // plain text body
      // html: '<b>Hello world111?</b>' // html body
    }
    // send mail with defined transport object
    try {
      const contentMd5 = self.MD5(strContent)
      if (self.contents.indexOf(contentMd5) === -1) {
        log.info('send mail:', mailOptions)
        let info = await transporter.sendMail(mailOptions)
        self.contents.push(contentMd5)
        if (self.contents.length > 1000) {
          self.contents.shift()
        }
        log.info(info)
        return true
      } else {
        log.info(strContent, ' 发送失败，重复内容.')
        return false
      }
    } catch (err) {
      log.error(err)
      return false
    }
  }
}

module.exports = new Mail()
